<template>
    <el-upload class="upload-demo" action="" multiple drag :http-request="http_post"
        :before-upload="cleanCache">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
            </div>
        </template>
    </el-upload>
    <div id="resutl_image_container">
        <p v-if="result_status" :class="result_status_c">{{ result_status }}</p>
        <p v-if="result_text">后端返回的文字：{{ result_text }}</p>
        <img v-if="resutl_image" id="resutl_image" :src="resutl_image" alt="">
    </div>
</template>

<script setup lang="ts">
import { ElUpload, ElIcon } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { ref } from 'vue';
const result_status = ref('')
const result_status_c = ref('')
const result_text = ref('')
const resutl_image = ref('')

function cleanCache() {
    result_status.value = '等待中，请稍后...'
    result_status_c.value = ''
    result_text.value = ''
    resutl_image.value = ''
}

function http_post(param: any) {
    return new Promise(function (resolve, reject) {
        ///处理文件
        const formData = new FormData();
        formData.append("file", param.file)
        ///新建请求
        let request = new XMLHttpRequest();
        request.open('POST', '/nginx_custom_url/upload/');
        //本项目的后端是通过直接发送二进制文件+响应头携带文本信息
        //因此响应体设置为二进制模式
        request.responseType = 'blob'
        //处理响应
        request.onload = function () {
            //即使是404也会进入这个相应函数，所以需要检测状态
            if (request.status == 200) {
                //设置处理结果的class类名
                result_status_c.value = 'success'
                //设置处理结果文字
                result_status.value = '[200]处理成功'
                //获取存储在响应头中文本信息
                const text_data = request.getResponseHeader('response_textdata')
                text_data ? result_text.value = JSON.parse(text_data) : ''
                //将图像解析成连接
                resutl_image.value = window.URL.createObjectURL(new Blob([request.response]))
                resolve(request.response);
            }
            else {
                //完成未完成，返回错误
                reject(Error(request.statusText));
                //由于前面设置了responseType=blob，所以需要手动utf-8解码才能获取服务器返回的错误信息文本
                const fr = new FileReader()
                fr.readAsText(request.response)
                fr.onload = () => {
                    if (fr.result) {
                        result_status.value = '[' + request.status + ']' + fr.result.toString()
                        result_status_c.value = 'error'
                    } else {
                        result_status.value = '[' + request.status + ']' + '服务器未返回数据'
                    }
                }
            }
        }
        // 发生错误时的相应函数
        request.onerror = function () {
            reject(Error("Network Error"));
        };
        // 发送请求
        request.send(formData);
    });
}


</script>

<style scoped>
.upload-demo {
    margin-top: 5rem;
    width: 500px;
}

#resutl_image_container {
    display: flex;
    justify-content: center;
    flex-direction: column;
}

#resutl_image_container p {
    margin: 0;
    text-align: center;
}

#resutl_image {
    min-width: 100px;
    min-height: 100px;
    border: 1px solid red;
    width: 100%;
    max-width: 80vw;
}

.error {
    color: red
}

.success {
    color: green;
}
</style>